import 'package:easy_read_comic/internal/api/comic_api.dart';
import 'package:easy_read_comic/models/chapter_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class ReadController extends GetxController {
  late ScrollController _scrollController;

  ReadController(this._scrollController);

  //侧边栏的章节列表
  List<ChapterModel> chapterList = [];

  //侧边栏的章节列表当前的页码
  int currentPage = 0;

  // 侧边栏的章节列表是否加载完毕
  bool chapterListLoadDone = false;

  int MaxSlider = 0;

  //待加载的图片
  List<String> list = [];

  //加载完毕的图片
  List<String> loadList = [];

  // 章节信息
  ChapterModel chapter = ChapterModel(0, "正在加载...", "", "", 0, 0);

  late int comicId;

  late int chapterId;

  // 加载状态
  bool _loadState = false;

  //滚动组件的 x 坐标
  double scrollX = 0.00;

  //滚动组件的 Y 坐标
  double scrollY = 0.00;

  double startPositionX = 0.00;
  double endPositionX = 0.00;

  //滑块的值
  double sliderValue = 0;

  //暂时没有用到 Y 坐标
  double startPositionY = 0.00;
  double endPositionY = 0.00;

  bool showTool = false;

  // 图片显示方式
  BoxFit photoBoxFit = BoxFit.fitWidth;

  // 阅读方式
  Axis readPhotoMethod = Axis.horizontal;

  void _scrollListener() {
    if (_isBottom) {
      _lazyLoadImage();
    }
  }

  //_lazyLoadImage 图片懒加载
  void _lazyLoadImage() {
    if (this._loadState) {
      return;
    }
    this._loadState = true;
    for (var i = 0; i <= 5; i++) {
      this.loadList.add(this.list.removeAt(0));
      this.MaxSlider = this.loadList.length;
    }
    update();
    this._loadState = false;
  }

  bool get _isBottom {
    if (!_scrollController.hasClients) return false;
    if (this.readPhotoMethod == Axis.vertical) {
      return _scrollController.position.maxScrollExtent -
              _scrollController.position.pixels <=
          Get.height;
    }
    return _scrollController.position.maxScrollExtent -
            _scrollController.position.pixels <=
        Get.width;
  }

  @override
  void onInit() {
    super.onInit();
    chapterId = int.parse(Get.parameters["chapter_id"]!);
    comicId = int.parse(Get.parameters["comic_id"]!);
    this.chapterDetail(chapterId.toString());
    this.resetGetChapterList();
  }

  @override
  void onReady() {
    super.onReady();
    _scrollController.addListener(_scrollListener);
    this.getResourceList();
    this.ShowTool(false);
  }

  void getResourceList() {
    ComicApi().resourceList(chapterId.toString()).then((response) {
      if (response.data["code"] == 1) {
        for (var item in response.data["data"]) {
          this.list.add(item.toString());
        }

        _lazyLoadImage();
      }
    });
  }

  chapterDetail(String chapterId) {
    ComicApi().chapterDetail(chapterId).then((response) {
      if (response.data["code"] == 1) {
        chapter = ChapterModel.formJson(response.data["data"]);
        this.update();
      }
    });
  }

  void resetLoad(int comicId, int chapterId) {
    this._loadState = false;
    this._scrollController.jumpTo(0);
    this.comicId = comicId;
    this.chapterId = chapterId;
    this.chapter = ChapterModel(0, "正在加载中...", "", "", 0, 0);
    this.list.clear();
    this.loadList.clear();
    this.MaxSlider = 0;
    this.sliderValue = 0;
    this.scrollX = 0.00;

    this.startPositionX = 0.00;
    this.endPositionX = 0.00;

    //暂时没有用到 Y 坐标
    this.startPositionY = 0.00;
    this.endPositionY = 0.00;

    this.ShowTool(false);

    this.chapterDetail(this.chapterId.toString());
    this.getResourceList();
  }

  void onPointerDown(PointerDownEvent event) {
    startPositionX = endPositionX = event.position.dx;
    startPositionY = endPositionY = event.position.dy;
  }

  void onPointerMove(PointerMoveEvent event) {
    endPositionX = event.position.dx;
    endPositionY = event.position.dy;
  }

  void onPointerUp(PointerUpEvent event) {
    //抬起手指查看是否移动了手指
    if ((startPositionX == endPositionX) && (startPositionY == endPositionY)) {
      //没有移动手指
      this.ShowTool(!showTool);
    } else {
      if (this.readPhotoMethod == Axis.vertical) {
        //上下移动
        moveWindow(startPositionY > endPositionY);
      } else {
        //左右移动
        moveWindow(startPositionX > endPositionX);
      }
    }
  }

  /**
   * leftOrRight 是手指移动的方向,true=左,false=右
   * isSlider 是否通过步进条拖动
   */
  void moveWindow(bool leftOrRight, {bool isSlider = false}) {
    //滚动了屏幕,判断是左是右
    if (leftOrRight) {
      //手指向左|向上滑动
      if (this.readPhotoMethod == Axis.vertical) {
        if (scrollY < (Get.height * (this.loadList.length - 1))) {
          //移动没有超出最大宽度
          scrollY += Get.height;
          sliderValue++;
        }
      } else {
        if (scrollX < (Get.width * (this.loadList.length - 1))) {
          //移动没有超出最大宽度
          scrollX += Get.width;
          sliderValue++;
        }
      }
    } else {
      //手指向右|向下滑动
      if (this.readPhotoMethod == Axis.vertical) {
        if (scrollY > 0) {
          scrollY -= Get.height;
          sliderValue--;
        }
      } else {
        if (scrollX > 0) {
          scrollX -= Get.width;
          sliderValue--;
        }
      }
    }
    if (isSlider) {
      _scrollController.animateTo(
        this.readPhotoMethod == Axis.vertical ? scrollY : scrollX,
        duration: Duration(milliseconds: 100), // 动画持续时间
        curve: Curves.linearToEaseOut, // 动画曲线
      );
    } else {
      _scrollController.animateTo(
        this.readPhotoMethod == Axis.vertical ? scrollY : scrollX,
        duration: Duration(milliseconds: 500), // 动画持续时间
        curve: Curves.easeInOut, // 动画曲线
      );
    }
    this.update();
  }

  // showTool 工具栏显示 隐藏
  void ShowTool(bool showTool) {
    this.showTool = showTool;
    if (showTool) {
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
          overlays: SystemUiOverlay.values);
    } else {
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    }
    this.update();
  }

  void changePhotoBoxFit(BoxFit boxFit) {
    this.photoBoxFit = boxFit;
    this.update();
  }

  void changeReadMethod(Axis axis) {
    this.readPhotoMethod = axis;
    double current;
    if (this.readPhotoMethod == Axis.vertical) {
      current = this.scrollY = (this.sliderValue * Get.height);
    } else {
      current = this.scrollX = (this.sliderValue * Get.width);
    }
    _scrollController.jumpTo(
      current,
    );
    this.update();
  }

  void getChapterList() {
    if (this.chapterListLoadDone) return;
    ComicApi()
        .chapterList(this.comicId.toString(), currentPage: this.currentPage)
        .then((response) {
      if (response.data["code"] == 1) {
        var data = response.data["data"];
        for (var item in data["List"]) {
          this.chapterList.add(ChapterModel.formJson(item));
        }
        if (data["Page"]["NextPage"] != null) {
          this.currentPage = data["Page"]["NextPage"];
        } else {
          this.chapterListLoadDone = true;
        }
        update();
      }
    });
  }

  void resetGetChapterList() {
    this.currentPage = 0;
    this.chapterListLoadDone = false;
    this.chapterList = [];
    this.getChapterList();
  }
}
